from django.contrib.auth import authenticate, login
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
from django.views import View
from .froms import *

class LoginView(View):
    def get(self,requerst):
        loginfrom=LoginFrom()
        return render(requerst,'login.html',{'loginfrom':loginfrom})

    def post(self,requerst):
        loginfrom = LoginFrom(requerst.POST)
        #校验是否合法
        if loginfrom.is_valid():

            #以字典形式返回合法数据
            cd= loginfrom.cleaned_data
            #检验用户的帐号密码是否正确
            user = authenticate(username=cd['sname'],password = cd['pwd'])

            if user:
                #实现用户登录把信息保存到session中完成登录
                login(requerst,user)
                return HttpResponse('sss')
        return HttpResponse('失败')


class ZhuceView(View):
    def get(self,request):
        #创建表单对象
        clsFrom = ClazzFrom()
        stuFrom = StuFrom()
        return render(request,'zhuce.html',{'clsFrom':clsFrom,'stuFrom':stuFrom})

    def post(self,request):
        # 创建表单对象
        clsFrom = ClazzFrom(request.POST)
        stuFrom = StuFrom(request.POST)
        #验证表单是否合法
        if clsFrom.is_valid()*stuFrom.is_valid():
            cls = clsFrom.save()
            stu = stuFrom.save(commit=False) #事物不提交，默认提交
            stu.cla = cls
            stu.save()
            return HttpResponse('成功')
        return HttpResponse('失败')